<?php
namespace app\user\model;
use think\Model;
use think\model\concern\SoftDelete;

class Customer extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;
    protected $autoWriteTimestamp = true;
    protected $globalScope = ['shop_id'];
    public function scopeShop_id($query)
    {
        $query->where('shop_id', ShopId());
    }
    
    public function setProvinceAttr($value,$data)
    {
        if(!$data['shengshi']){
            $list = array();
        }else{
            $list = explode(',',$data['shengshi']);
        }
        return $list[0];
    }
    
    public function setCityAttr($value,$data)
    {
        if(!$data['shengshi']){
            $list = array();
        }else{
            $list = explode(',',$data['shengshi']);
        }
        return $list[1];
    }
    
    public function setAreaAttr($value,$data)
    {
        if(!$data['shengshi']){
            $list = array();
        }else{
            $list = explode(',',$data['shengshi']);
        }
        return $list[2];
    }
    public function getStarAttr($value)
    {
        $name = ['0'=>'','1'=>'★','2'=>'★★','3'=>'★★★','4'=>'★★★★','5'=>'★★★★★'];
        return $name[$value];
    }
    //获取
    public function classify()
    {
        return $this->belongsTo(CustomerConfig::class,'classify','id')->bind(['classify_name'=>'name']);
    }
    public function comefrom()
    {
        return $this->belongsTo(CustomerConfig::class,'comefrom','id')->bind(['comefrom_name'=>'name']);
    }
    public function status()
    {
        return $this->belongsTo(CustomerConfig::class,'status','id')->bind(['status_name'=>'name']);
    }
    public function user()
    {
        return $this->belongsTo(User::class,'user_id','id');
    }
    //上次回访
    public function lastTime()
    {
        return $this->hasOne(CustomerTrack::class,'customer_id','id')->bind(['lasttime'=>'create_time'])->order('id desc');
    }
    
    //更新时间
    public static function updateTime($id)
    {
        $list = self::where('id',$id)->update(['update_time'=>time()]);
        return $list;
    }
    
    //统计数量
    public function countProvince()
    {
        return $this->hasMany(Customer::class,'province','province');
    }
    
    
    
}